package com.neusoft.student.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author: duan
 * @Date: Create in 15:18 2020/10/24
 */
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("LoginFilter初始化");
        /*  FilterConfig
         *      与ServletConfig类似，都是可以获取一些关于该过滤器Filter相关的信息
         */
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("LoginFilter实现过滤方法");
        /*
            servletRequest：就是请求对象
            ServletResponse：响应对象
            FilterChain：过滤器链
         */
        //过滤之前的代码
        /*
            获取session
            检查session域中是否有指定的key和value
         */
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession();
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        String contextPath = request.getContextPath();
        System.out.println(contextPath);
        requestURI = requestURI.substring(contextPath.length());
//        requestURI = requestURI.replace(contextPath, "");
        System.out.println(requestURI);
        String[] whiteNames = {"login.jsp", "login"};
        for (String item : whiteNames) {
            if (requestURI.endsWith(item)) {
                System.out.println("白名单");
                filterChain.doFilter(req, resp);//放行
                return;
            }
        }
        Object username = session.getAttribute("username");
        if (username == null) {
            //没有登录
            response.sendRedirect(contextPath + "/login.jsp");
        } else {
            filterChain.doFilter(req, resp);//放行
        }
        //过滤之后的代码
        System.out.println("LoginFilter过滤之后的代码");
    }

    @Override
    public void destroy() {
        System.out.println("LoginFilter销毁");
    }
}
